package com.wetao.flexiblerichtextview;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daquexian.flexiblerichtextview.MyConfige;
import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;
import com.tencent.sonic.sdk.SonicCacheInterceptor;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.tencent.sonic.sdk.SonicSessionConnection;
import com.tencent.sonic.sdk.SonicSessionConnectionInterceptor;
import com.wetao.flexiblerichtextview.web.OfflinePkgSessionConnection;
import com.wetao.flexiblerichtextview.web.SonicJavaScriptInterface_x5;
import com.wetao.flexiblerichtextview.web.SonicRuntimeImpl;
import com.wetao.flexiblerichtextview.web.SonicSessionClientImpl_x5;
import com.wetao.flexiblerichtextview.web.WebConstants;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public class WebviewTestActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "WebviewTestActivity";
    private static final int HANDLER_INIT_WEBVIEW = 1;

    WebView webview;
    View viewStatus;//与状态栏同步高度的View
    LinearLayout llLoadding;

    LinearLayout lyt_page_bottom;
    Button btn_page_prev;
    TextView tv_page_num;
    Button btn_page_next;
    Button btn_androidToJs1;
    Button btn_androidToJs2;

    private SonicSession sonicSession;

    boolean showLoadding = false;

    int mWebviewProgress = 0;

    int mHeight = 0;
    int mContentHeight = 0;
    int mCurPage = 0;
    int mTotalPage = 0;

    private MyHandler handler;

    static class MyHandler extends Handler {
        WeakReference<WebviewTestActivity> weakReference;
        public MyHandler(WebviewTestActivity activity) {
            weakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if(weakReference.get() == null) {
                return;
            }
            WebviewTestActivity activity = weakReference.get();
            if(msg.what == HANDLER_INIT_WEBVIEW) {
                activity.initWebViewInfo();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_test);
        webview = findViewById(R.id.webview);
        viewStatus = findViewById(R.id.view_status);
        llLoadding = findViewById(R.id.ll_loadding);
        lyt_page_bottom = findViewById(R.id.lyt_page_bottom);
        btn_page_prev = findViewById(R.id.btn_page_prev);
        tv_page_num = findViewById(R.id.tv_page_num);
        btn_page_next = findViewById(R.id.btn_page_next);
        btn_androidToJs1 = findViewById(R.id.btn_androidToJs1);
        btn_androidToJs2 = findViewById(R.id.btn_androidToJs2);

        btn_page_prev.setOnClickListener(this);
        btn_page_next.setOnClickListener(this);
        btn_androidToJs1.setOnClickListener(this);
        btn_androidToJs2.setOnClickListener(this);

        /*webview.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                return true;
            }
        });*/
        init();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_page_prev:{
                mCurPage--;
                webview.getX5WebViewExtension().scrollBy(0, -(int)(webview.getHeight() * MyConfige.scroll_by_page_percent));
                setPageNum();
            }break;
            case R.id.btn_page_next:{
                mCurPage++;
                webview.getX5WebViewExtension().scrollBy(0, (int)(webview.getHeight() * MyConfige.scroll_by_page_percent));
                setPageNum();
            }break;
            case R.id.btn_androidToJs1:{
                webview.loadUrl("javascript:androidCallJs1(" + false + ")");
            }break;
            case R.id.btn_androidToJs2:{
                webview.loadUrl("javascript:androidCallJs2(" + true + ")");
            }break;
        }
    }

    public void init() {
        handler = new MyHandler(this);

        // init sonic engine
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        if (viewStatus != null) {
            //updateStatusHeight(statusBarHeight);
            updateStatusHeight(0);
        }

        try {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
        }

        handler.sendEmptyMessageDelayed(HANDLER_INIT_WEBVIEW, 20);
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        if (webview != null) {
            webview.setVisibility(View.GONE);// 把destroy()延后
            webview.destroy();
        }

        if(handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }

    private void setPageNum() {
        if(mCurPage > 0) {
            btn_page_prev.setVisibility(View.VISIBLE);
        } else {
            btn_page_prev.setVisibility(View.INVISIBLE);
        }

        if(mCurPage < mTotalPage - 1) {
            btn_page_next.setVisibility(View.VISIBLE);
        } else {
            btn_page_next.setVisibility(View.INVISIBLE);
        }

        tv_page_num.setText((mCurPage + 1)+ "/" + mTotalPage);
    }


    //获取是否存在NavigationBar
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }

    public void initWebViewInfo() {
        Intent intent = getIntent();
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        //ws.setTextZoom(100);
        //String url = "file:///storage/sdcard0/Android/data/com.wetao.teacherapp/files/07StrongBaseMobile/index.html";
        String url = "http://192.168.3.6:9528/#/testwebview";
        //String url = "https://www.kotlincn.net/docs/reference/basic-syntax.html";
        //String url = "https://www.baidu.com/";
        /*String url = AppConfig.BASE_WEB_URL
                +"report?"
                +"publishId=" + publishId
                +"&token=" + SPUtils.getInstance().getString(Constants.HEAD_XTOKEN)
                + "&studentExamIds=" + getStudentExamIds();*/
       /* String url = "http://192.168.3.6:9528/#/report?"
                +"publishId=" + publishId
                +"&token=" + SPUtils.getInstance().getString(Constants.HEAD_XTOKEN)
                + "&studentExamIds=" + getStudentExamIds();*/
        //String url = "file:///android_asset/dist/index.html#/report?publishId=888&token=69d97d9bfbbb48b7929b91d2715ae921&studentExamIds=4522,4523,4524,4525,4526,4527,4528,4529,4530,4531,4532,4533,4534,4535,4536,4537,4538,4539,4540,4541,4542,4543,4544,4545,4546,4547,4548,4549,4550,4551,4552,4553,4554,4555,4556,4557,4558,4559,4560,4561,4562,4563,4564,4565,4566,4567,4568,4569,4570,4571,4572,4573,4574,4575,4576,4577,4578,4579,4580,4581,4582,4583,4584";
        Log.i(TAG, url);
        showLoadding = true;
        int mode = WebConstants.MODE_DEFAULT;
        if (TextUtils.isEmpty(url) || -1 == mode) {
            finish();
            return;
        }

        // init sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        SonicSessionClientImpl_x5 sonicSessionClient = null;
        // if it's sonic mode , startup sonic session at first time
        if (WebConstants.MODE_DEFAULT != mode) { // sonic mode
            SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
            sessionConfigBuilder.setSupportLocalServer(true);

            // if it's offline pkg mode, we need to intercept the session connection
            if (WebConstants.MODE_SONIC_WITH_OFFLINE_CACHE == mode) {
                sessionConfigBuilder.setCacheInterceptor(new SonicCacheInterceptor(null) {
                    @Override
                    public String getCacheData(SonicSession session) {
                        return null; // offline pkg does not need cache
                    }
                });

                sessionConfigBuilder.setConnectionInterceptor(new SonicSessionConnectionInterceptor() {
                    @Override
                    public SonicSessionConnection getConnection(SonicSession session, Intent intent) {
                        return new OfflinePkgSessionConnection(WebviewTestActivity.this, session, intent);
                    }
                });
            }

            // create sonic session and run sonic flow
            sonicSession = SonicEngine.getInstance().createSession(url, sessionConfigBuilder.build());
            if (null != sonicSession) {
                sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl_x5());
            } else {
                Toast.makeText(this, "create sonic session fail!", Toast.LENGTH_LONG).show();
            }
        }

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
                Log.e(TAG, "测试webView onPageFinished");
                if(mWebviewProgress == 100) {
                    mHeight = webview.getHeight();
                    mContentHeight = webview.getContentHeight();
                    int measuredHeight = webview.getMeasuredHeight();
                    Log.e(TAG, "测试webView onPageFinished height = " + mHeight + ", contentHeight = " + mContentHeight + ", measuredHeight = " + measuredHeight);
                    if(mContentHeight > mHeight) {
                        lyt_page_bottom.setVisibility(View.VISIBLE);
                        mCurPage = 0;
                        float f_total = mContentHeight/(mHeight * MyConfige.scroll_by_page_percent);
                        if(f_total - (int)f_total > 0) {
                            f_total = f_total + 1;
                        }
                        mTotalPage = (int)f_total;
                        if(mTotalPage > 2) {
                            if((mTotalPage - 2) * mHeight * MyConfige.scroll_by_page_percent + mHeight < mContentHeight) {
                                mTotalPage = mTotalPage - 1;
                            }
                        }
                        setPageNum();
                    }
                }
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }

        });

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                if (i == 100) {
                    //rlyt_progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    //rlyt_progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                }
                mWebviewProgress = i;
                Log.e(TAG, "测试webView onProgressChanged = " + i);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.e("consoleMessage", consoleMessage.message() + " -- From line "
                        + consoleMessage.lineNumber() + " of "
                        + consoleMessage.sourceId());
                return super.onConsoleMessage(consoleMessage);
            }
        });

        WebSettings webSetting = webview.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
//        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
//        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
//                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);

        //webSetting.setAllowContentAccess(true);
        //webSetting.setSavePassword(false);
        //webSetting.setSaveFormData(false);

        long time = System.currentTimeMillis();

        mWebviewProgress = 0;
        webview.loadUrl(url);

        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();




        // 设置与Js交互的权限
        webview.removeJavascriptInterface("searchBoxJavaBridge_");
        SonicJavaScriptInterface_x5 sonicJavaScriptInterface = new SonicJavaScriptInterface_x5(sonicSessionClient, intent);
        sonicJavaScriptInterface.setObserverJSAction(new SonicJavaScriptInterface_x5.ObserverJSAction() {
            @Override
            public void reLoginDialog() {
                //DialogUtil.getInstance().reLoginDialog(MarkingStatisticReportActivity.this, "未登录或登录已过期");
            }
        });
        webview.addJavascriptInterface(sonicJavaScriptInterface, "sonic");

        // init webview settings


        // 设置允许JS弹窗
        //webview.setJavaScriptCanOpenWindowsAutomatically(true);


        // webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webview);
            sonicSessionClient.clientReady();
        } else { // default mode
            webview.loadUrl(url);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();//返回上个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);//退出整个应用程序
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (webview != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
                webview.goBack();//返回上个页面
                return true;
            }
        }

        return super.dispatchKeyEvent(event);
    }

    public void updateStatusHeight(int height) {
        ViewGroup.LayoutParams lp = viewStatus.getLayoutParams();
        lp.height = height;
        viewStatus.setLayoutParams(lp);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null || webview == null || intent.getData() == null)
            return;
        webview.loadUrl(intent.getData().toString());
    }
}
